import { onMounted, onUnmounted } from "vue";
import { defineStore } from "pinia";
import { getSongUrl, getSongDetail } from "@/api/player";
import { getPlayListTracks } from "@/api/album";
import { LevelType, SongUrlData } from "@/types/player";
import { PlayListSong } from "@/types/album";

const getStroagedCSongId = () => {
  const lastId = window.localStorage.getItem("lastPlayId");
  if (lastId) {
    return Number(lastId);
  }
};

export const usePlayerStores = defineStore({
  id: "player",
  state: () => ({
    audio: new Audio(),
    playingId: -1, // 正在播放的音乐的id
    song: {} as PlayListSong,

    songUrlData: {} as SongUrlData,
    volume: 100,
    isPlaying: false,
    isPause: true,
    currentTime: 0,
    duration: 0,
    ended: false,
    lastCurrent: 0,
    req: "" as any,
    sliderInput: false,
    memoVolume: 0,
    playListId: -1 as number | string,
    playList: [] as Array<PlayListSong>,
    showPlayList: false,
    loopType: 1, // 0 单曲循环， 1正常， 3随机
  }),
  getters: {
    playIndex(state): number {
      return this.playList.findIndex((song) => song.id === this.playingId);
    },
    playCount(): number {
      return this.playList.length;
    },
    prevSong(state): PlayListSong {
      const { playIndex, playCount } = this;
      if (playIndex === 0) {
        return state.playList[playCount - 1];
      } else {
        return state.playList[playIndex - 1];
      }
    },
    nextSong(state): PlayListSong {
      const { playIndex, playCount } = this;
      if (playIndex === playCount - 1) {
        return state.playList[0];
      } else {
        return state.playList[playIndex + 1];
      }
    },
  },
  actions: {
    init() {
      this.playingId = getStroagedCSongId() || -1;
      this.audio.volume = this.volume / 100;
      if (this.playingId) {
        this.songDetail(this.playingId);
        this.setUrl(this.playingId);
      }
      let lastPlayListId: any = window.localStorage.getItem("lastPlayListId");
      if (lastPlayListId !== null) {
        this.playListId = lastPlayListId;
        this.setPlayListById(this.playListId);
      }
      const memoVolume = window.localStorage.getItem("playerVolume")
        ? Number(window.localStorage.getItem("playerVolume"))
        : 100;
      if (typeof memoVolume === "number") {
        this.volume = memoVolume;
        this.audio.volume = memoVolume / 100;
      }
      this.req = window.requestAnimationFrame(this.intervel);
    },

    async setUrl(id: number) {
      const res = await getSongUrl(id, "standard");

      if (res.code === 200) {
        this.songUrlData = res.data[0];
        this.audio.src = res.data[0].url;
        this.duration = Math.round(res.data[0].time / 1000);
      }
    },
    async play(id: number, level: LevelType) {
      if (this.playingId === id) {
        return;
      }

      const res = await getSongUrl(id, level);

      if (res.code === 200) {
        this.songUrlData = res.data[0];
      }
      this.audio.src = res.data[0].url;

      this.audio.play().then((res) => {
        this.isPlaying = true;
        this.isPause = false;
        this.duration = this.audio.duration;
        this.currentTime = 0;
        this.audio.currentTime = 0;
        this.lastCurrent = 0;
        this.playingId = id;
        window.localStorage.setItem("lastPlayId", `${id}`);
      });
    },
    setVolume(vol: number) {
      vol = vol > 100 ? 100 : vol;
      vol = vol < 0 ? 0 : vol;
      this.volume = vol;
      this.audio.volume = vol / 100;
      window.localStorage.setItem("playerVolume", String(vol));
    },
    toggleMute(flag: boolean) {
      if (flag === true) {
        this.memoVolume = this.volume;
        this.volume = 0;
        this.audio.volume = 0;
        window.localStorage.setItem("playerVolume", "0");
      } else {
        const trueVol = this.memoVolume === 0 ? 60 : this.memoVolume;
        this.volume = trueVol;
        this.audio.volume = trueVol / 100;

        window.localStorage.setItem("playerVolume", String(trueVol));
      }
    },
    setPause() {
      if (!this.playingId) {
        return;
      }
      this.isPlaying = false;
      this.audio.pause();
      this.isPause = true;
    },
    setPlay() {
      if (!this.playingId) {
        return;
      }
      this.isPlaying = true;
      this.audio.play();
      this.isPause = false;
    },
    songDetail(ids: number) {
      getSongDetail(`${ids}`).then((data) => {
        if (data.code === 200) {
          this.song = data.songs[0];
        }
      });
    },
    intervel() {
      const time = this.audio.currentTime;
      if ((time - this.lastCurrent) * 1000 >= 1000 && !this.sliderInput) {
        this.currentTime = time;
        this.duration = this.audio.duration;

        this.lastCurrent = Math.floor(time);
        console.log(time);
      }
      this.ended = this.audio.ended;
      this.req = window.requestAnimationFrame(this.intervel);
    },
    cancelInteral() {
      window.cancelAnimationFrame(this.req);
    },
    onSliderInput() {
      this.sliderInput = true;
    },
    onSliderChange(val: number) {
      console.log(val, "sdsd");
      this.currentTime = val;
      this.sliderInput = false;
      this.audio.currentTime = val;
    },
    dispatchPlayList(list: PlayListSong[], id?: number | string) {
      this.playList = list;
      if (id) {
        this.playListId = id;
        window.localStorage.setItem("lastPlayListId", String(id));
      }
    },
    async setPlayListById(id: number | string) {
      this.playListId = id;
      window.localStorage.setItem("lastPlayListId", String(id));
      const data = await getPlayListTracks(id);
      if (data.code === 200) {
        this.dispatchPlayList(data.songs);
      }
    },
    togglePlayList() {
      this.showPlayList = !this.showPlayList;
    },

    closePlaylist() {
      this.showPlayList = false;
    },
    // 播放结束
    playEnd() {
      switch (this.loopType) {
        case 0:
          console.log("todo");
          break;
        case 1:
          this.playNext();
          break;
        case 2:
          break;
        default:
          break;
      }
    },
    playNext() {
      this.play(this.nextSong.id, "standard");
      this.songDetail(this.nextSong.id);
    },
    playPrev() {
      this.play(this.prevSong.id, "standard");
      this.songDetail(this.prevSong.id);
    },
  },
});
